package com.xsh.opensltest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.xsh.opensltest.plugin.AarManifest;
import com.xsh.opensltest.plugin.XmlParser;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ManageActivity extends AppCompatActivity
{
    public String tag = "mymanage";
    private Dialog dialog;
    public File appCacheDir;
    public File appFilesDir;
    private LinearLayout pluginList;

    public void delDexCache(View v)
    {
        FileUtils.cleanCache(this,new File(App.appCacheDir,"dex").getAbsoluteFile());
        Toast.makeText(this,"dex缓存清理完毕，请重新安装插件",Toast.LENGTH_LONG).show();
    }
    public void delInstalledPlugins(View v)
    {
        FileUtils.cleanCache(this,App.appFilesDir);
        Toast.makeText(this,"所有安装的插件都被清理了",Toast.LENGTH_LONG).show();

    }
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage);
        appCacheDir = getCacheDir();
        appFilesDir = getFilesDir();
        pluginList = findViewById(R.id.pluginList);
        // 高版本导入
        findViewById(R.id.higher_import).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                 Intent i = new Intent(ManageActivity.this,FilePicker.class);
                 startActivity(i);
            }
        });
        findViewById(R.id.refreshPluginButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                if(pluginList.getChildCount()==0)
                {
                    for (File a : App.appFilesDir.listFiles()) {
                        TextView tv = new TextView(ManageActivity.this);
                        tv.setText(a.getName());
                        pluginList.addView(tv);
                    }
                }
                else{
                    pluginList.removeAllViews();
                    for (File a : App.appFilesDir.listFiles()) {
                        TextView tv = new TextView(ManageActivity.this);
                        tv.setText(a.getName());
                        pluginList.addView(tv);
                    }
                }
                Toast.makeText(ManageActivity.this,"刷新完毕",Toast.LENGTH_SHORT).show();
            }
        });
        findViewById(R.id.cleanImportCacheButton).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                FileUtils.cleanCache(App.appContext,new File(App.appCacheDir,"temp"));
                Toast.makeText(ManageActivity.this,"插件缓存清理完毕",Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void onImportClick(View v) throws Exception {
        EditText t = findViewById(R.id.pluginDir);
        String path = t.getText().toString();
        // "解压中请稍候"
        File importFile = new File(path);
        if(importFile.isFile()&&importFile.exists())
        {
            FileUtils fu = new FileUtils();
            showProgressDialog();
            new UnzipTask().execute(path);
        }
        else{Toast.makeText(this,"路径非法",Toast.LENGTH_SHORT).show();}
        }

    private void showProgressDialog()
    {
        dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_unzip_progress);
        dialog.setCancelable(false);
        dialog.show();
    }
    public void updateProgress(int progress)
    {
        if(dialog != null && dialog.isShowing())
        {
            ProgressBar pb = dialog.findViewById(R.id.manage_work_progressbar);
            TextView tv = dialog.findViewById(R.id.manage_progress);
            tv.setText("进度:" + progress + "%");
            pb.setProgress(progress);
        }
    }
    class UnzipTask extends AsyncTask<String, Integer, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // 初始化进度为 0%
            updateProgress(0);
        }

        @Override
        protected Boolean doInBackground(String... params) {
            String zipFilePath = params[0];
            File destinationDir = getCacheDir(); // 解压到缓存目录

            try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) {
                ZipEntry ze;
                int totalEntries = 0;
                int currentEntry = 0;

                // 计算总条目数
                while ((ze = zis.getNextEntry()) != null) {
                    totalEntries++;
                    zis.closeEntry();
                }

                zis.close();

                // 再次打开 ZIP 文件进行解压
                try (ZipInputStream zis2 = new ZipInputStream(new FileInputStream(zipFilePath))) {
                    while ((ze = zis2.getNextEntry()) != null) {
                        File file = new File(destinationDir, ze.getName());
                        if (ze.isDirectory()) {
                            file.mkdirs();
                        } else {
                            file.getParentFile().mkdirs();
                            try (OutputStream fos = new FileOutputStream(file)) {
                                byte[] buffer = new byte[1024];
                                int len;
                                while ((len = zis2.read(buffer)) > 0) {
                                    fos.write(buffer, 0, len);
                                }
                            }
                        }
                        zis2.closeEntry();
                        currentEntry++;
                        int progress = (int) (((double) currentEntry / totalEntries) * 100);
                        publishProgress(progress);
                    }
                }
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            int progress = values[0];
            updateProgress(progress);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss(); // 关闭对话框
            }

            if (result) {
                Toast.makeText(ManageActivity.this, "解压完成", Toast.LENGTH_SHORT).show();
                //String manifest = appCacheDir.getAbsolutePath();
                try {
                    File manifestFile = new File(appCacheDir,"/AndroidManifest.xml");
                    if (manifestFile.exists())
                    {
                        Log.d(tag,"AndroidManifest.xml exists");
                        AarManifest aarManifest = XmlParser.parseManifest(manifestFile);
                        String pluginName = aarManifest.getPluginName();
                        String layout = "assets/ui.json";
                        String libName = aarManifest.getLibName();
                        Log.d(tag,"pluginName: " +pluginName);
                        //Log.d(tag,"layout: " + layout);
                        Log.d(tag,"libName:" + libName);
                        // 安装 lib
                        new File(appFilesDir,pluginName).mkdir();
                        Log.d(tag,"安装lib");

                        if(DeviceUtils.getBestAbi().equals("armabi-v7a"))
                        {
                            Log.d(tag,"copy armv7a lib");
                            FileUtils.copyFile(new File(appCacheDir,"temp/jni/armabi-v7a/"+libName).getAbsolutePath(),new File(appFilesDir, pluginName + "/lib" + "/" + libName).getAbsolutePath());
                        }
                        else if(DeviceUtils.getBestAbi().equals("arm64-v8a"))
                        {
                            Log.d(tag,"copy armv8a lib");
                            FileUtils.copyFile(new File(appCacheDir,"temp/jni/arm64-v8a/"+libName).getAbsolutePath(),new File(appFilesDir, pluginName + "/lib" + "/" + libName).getAbsolutePath());
                        }
                        else if(DeviceUtils.getBestAbi().equals("x86"))
                        {
                            Log.d(tag,"copy x86 lib");
                            Log.d(tag,"src: " + new File(appCacheDir,"temp/jni/x86/"+libName).getAbsolutePath());
                            Log.d(tag,"target: " +new File(appFilesDir, "temp" + File.separator + pluginName + "/lib" + "/" + libName).getAbsolutePath());
                            FileUtils.copyFile(new File(appCacheDir,"temp/jni/x86/"+libName).getAbsolutePath(),new File(appFilesDir, pluginName + "/lib" + "/" + libName).getAbsolutePath());
                        }
                        else if(DeviceUtils.getBestAbi().equals("x86_64"))
                        {
                            FileUtils.copyFile(new File(appCacheDir,"temp/jni/x86_64/"+libName).getAbsolutePath(),new File(appFilesDir,pluginName + "/lib" + "/" + libName).getAbsolutePath());
                            Log.d(tag,"copy x86_64 lib");
                        }

                        FileUtils.copyFile(new File(appCacheDir,"temp" + File.separator + layout).getAbsolutePath(),new File(appFilesDir,pluginName + "/layout/ui.json").getAbsolutePath());
                        FileUtils.copyFile(new File(appCacheDir,"temp" + File.separator + "config" + File.separator + "AndroidManifest.xml").getAbsolutePath(),new File(appFilesDir,pluginName+ "/config/AndroidManifest.xml").getAbsolutePath());
                        FileUtils.copyFile(new File(appCacheDir,"temp" + File.separator + "assets/classesd8.jar").getAbsolutePath(),new File(appFilesDir, pluginName + "/java/" + "classesd8.jar").getAbsolutePath());
                        Log.d(tag,"插件导入完成");
                        //Log.d(tag,"复制文件完成，开始清理缓存");
                    }
                    else{
                        Log.d(tag,"AndroidManifest.xml not exists");
                    }


                } catch (Exception e) {
                    Log.e(tag,e.getMessage());
                }



            } else {
                Toast.makeText(ManageActivity.this, "解压失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}